package com.chizha.iot.mqtt.client;

import java.util.Map;

/**
 * Created by Administrator on 17-2-10.
 */

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.log.Log;
import com.chizha.common.HexDump;
//import com.sun.javafx.image.impl.BaseByteToIntConverter;
import com.chizha.iot.mqtt.client.ServerMQTT;

/**
 *
 * Title:Server Description: 服务器向多个客户端推送主题，即不同客户端可向服务器订阅相同主题
 * 
 * @author admin 2017年2月10日下午17:41:10
 */
public class ServerMQTT {

	// tcp://MQTT安装的服务器地址:MQTT定义的端口号
	public static final String HOST = "tcp://210.77.68.221:10020";
	// 定义一个主题
	// public static final String TOPIC = "topic11";
	// 定义MQTT的ID，可以在MQTT服务配置中指定
	private static final String clientid = "server11";

	private MqttClient client;
	public MqttTopic topic11;
	private String userName = "admin";
	private String passWord = "qiaojiaoshou123";

	private static Log logger = Log.getLog(ServerMQTT.class);
	public MqttMessage message;

	private String topicName;

	/**
	 * 构造函数
	 * 
	 * @throws MqttException
	 */
	public ServerMQTT(String topicName_) throws MqttException {
		// MemoryPersistence设置clientid的保存形式，默认为以内存保存
		client = new MqttClient(HOST, clientid, new MemoryPersistence());
		topicName = topicName_;
		connect(topicName);
	}

	/**
	 * 用来连接服务器
	 * 
	 * @return
	 * @throws MqttException
	 * @throws MqttSecurityException
	 */
	private boolean connect(String topicName) throws MqttSecurityException, MqttException {
		logger.info("-----------connect-------------");
		MqttConnectOptions options = new MqttConnectOptions();
		options.setUserName(userName);
		options.setPassword(passWord.toCharArray());
		// 设置超时时间
		options.setConnectionTimeout(10);
		// 设置会话心跳时间
		options.setKeepAliveInterval(20);
		options.setCleanSession(true);

		client.setCallback(new PushCallback());
		client.connect(options);
		client.getTopic(topicName);
		topic11 = client.getTopic(topicName);

		return true;
	}

	/**
	 *
	 * @param topic
	 * @param message
	 * @throws MqttPersistenceException
	 * @throws MqttException
	 */
	public void publish(MqttTopic topic, MqttMessage message) throws MqttPersistenceException, MqttException {
		MqttDeliveryToken token = topic.publish(message);
		token.waitForCompletion();
		// logger.info("message is published completely! " + token.isComplete());
	}

	public void disconnect() {
		try {
			client.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 启动入口
	 * 
	 * @param args
	 * @throws MqttException
	 */
	public static void main(String[] args) throws MqttException {
		ServerMQTT server = new ServerMQTT("topic11");

		server.message = new MqttMessage();
		server.message.setQos(0);
		server.message.setRetained(false);
		server.message.setPayload("hello,topic11".getBytes());
		server.publish(server.topic11, server.message);
		System.out.println(server.message.isRetained() + "------ratained״̬");
	}
	public boolean publishTopic(byte[] msgContent) {
		try {
			logger.debug("publish " + topicName + " : " + HexDump.dumpHexString(msgContent));
			// ServerMQTT server = new ServerMQTT(topicName);
			this.message = new MqttMessage();
			this.message.setQos(0);
			this.message.setRetained(false);
			this.message.setPayload(msgContent);

			publish(topic11, message);

			disconnect();
		} catch (Exception e) {
			logger.error(e.toString(), e);
			return false;
		}
		return true;
	}
	public boolean publishTopic(String msgContent) {
		try {
			logger.debug("publish " + topicName + " : " + msgContent);
			// ServerMQTT server = new ServerMQTT(topicName);
			this.message = new MqttMessage();
			this.message.setQos(0);
			this.message.setRetained(false);
			this.message.setPayload(msgContent.getBytes());

			publish(topic11, message);

			disconnect();
		} catch (Exception e) {
			logger.error(e.toString(), e);
			return false;
		}
		return true;
	}

	// 发布消息
	public boolean publishTopic(Map<String, Object> msgMap) {
		String content = JSONObject.toJSONString(msgMap);
		return publishTopic(content);
	}

}